package org.sxm.cloud.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.sxm.cloud.result.ApiResult;
import org.sxm.cloud.result.ApiResultCode;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description异常信息全局处理
 * @Author xmSheng
 * @Date 2024/1/22
 */

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private final static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 资源不存在异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = {NoHandlerFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ApiResult noHandlerFoundException(Exception exception) {
        ApiResult result = new ApiResult(ApiResultCode.ERROR);
        result.setMessage("访问资源不存在");
        //TODO 写日志
        log.error(exception.getMessage(), exception);
        return result;
    }


    /**
     * 业务异常
     *
     * @param request
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = {org.sxm.cloud.exception.BizException.class,
            java.lang.IllegalArgumentException.class,
            feign.codec.DecodeException.class})
    public ApiResult allExceptionHandler(HttpServletRequest request, BizException exception)
            throws Exception {
        ApiResult response = new ApiResult();
        response.setCode(exception.getErrorCode());
        response.setMessage(exception.getMessage());
        //TODO 写日志
        log.error(exception.getMessage(), exception);
        return response;
    }

    /**
     * 捕获未知异常，如映射目录不存在，参数解析错误等等
     *
     * @param request
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = {Exception.class})
    public ApiResult defaultExceptionHandler(HttpServletRequest request, Exception exception) throws Exception {
        String msg = exception.getMessage();
        ApiResult result = new ApiResult(ApiResultCode.ERROR);
        if (exception instanceof org.springframework.http.converter.HttpMessageNotReadableException) {
            result.setMessage("请求参数不符合要求");
        } else if (exception instanceof org.sxm.cloud.exception.BizException) {
            result.setMessage(((BizException) exception).getMessage());
            return result;
        } else {
            result.setMessage("服务访问失败");
        }
        //TODO 写日志
        log.error(exception.getMessage(), exception);
        return result;
    }


}
